package com.sk.bilibili.utils;

import androidx.viewbinding.ViewBinding;

import com.sk.bilibili.dto.GenericInfo;
import com.sk.bilibili.model.BaseModel;
import com.sk.bilibili.other.BiliBiliException;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import lombok.SneakyThrows;

public class GenericUtils {

    private static final Class<BaseModel> BASE_MODEL_CLAZZ=BaseModel.class;
    private static final Class<ViewBinding> VIEW_BINDING_CLASS=ViewBinding.class;

    @SneakyThrows
    public static <M extends BaseModel, T extends ViewBinding> GenericInfo<T,M> parse(Class clazz){
        GenericInfo<T,M> genericInfo=new GenericInfo<>();
        while (clazz!=null){
            Type genericType = clazz.getGenericSuperclass();
            if(genericType instanceof ParameterizedType){
                ParameterizedType parameterizedType= (ParameterizedType) genericType;
                Type[] types = parameterizedType.getActualTypeArguments();
                for (Type type:types){
                    if(type instanceof Class){
                        Class temp= (Class) type;
                        if(BASE_MODEL_CLAZZ.isAssignableFrom(temp)){
                            genericInfo.setModelClass(temp);
                        }else if(VIEW_BINDING_CLASS.isAssignableFrom(temp)){
                            genericInfo.setBindClass(temp);
                        }
                    }
                }
            }
            clazz=clazz.getSuperclass();
        }
        return genericInfo;
    }

}